const { pool, data_url } = require('../database.js');

const getConfessionBarrages = async (request, response) => {
  try {
    const school_code = request.query.school_code || '';
    const limit = parseInt(100); // 确保 limit 是数字类型

    let sql = `
      SELECT 
        c.barrage_id,
        c.content,
        c.color,
        c.type,
        c.font_size,
        c.create_time,
        u.user_account as username,
        u.avatar_url
      FROM confession_wall c
      LEFT JOIN users u ON c.user_id = u.user_id
      WHERE c.status = 1
    `;

    let params = [];

    // 根据是否有 school_code 构建不同的查询
    if (school_code) {
      sql += ` AND c.school_code = ?`;
      params.push(school_code);
    }

    // 直接在SQL字符串中使用limit值，而不是作为参数
    sql += ` ORDER BY c.create_time DESC LIMIT ${limit}`;

    const [results] = await pool.execute(sql, params);

    // 处理结果
    const processedResults = results.map(result => ({
      ...result,
      avatar_url: result.avatar_url ? data_url + result.avatar_url : null,
      create_time: result.create_time
    }));

    response.json({
      msg: 'success',
      code: "200",
      data: processedResults
    });

  } catch (error) {
    console.error('获取表白墙弹幕失败:', error);
    response.json({
      msg: '服务器错误',
      code: "500",
      error: error.message
    });
  }
}

const sendConfessionBarrage = async (request, response) => {
  try {
    const {
      content,
      color = '#FFFFFF',
      type = 'normal',
      fontSize = 16
    } = request.body;

    const user_id = request.query.user_id;
    const school_code = request.query.school_code;

    // 参数验证
    if (!content || !user_id) {
      return response.json({
        msg: '参数不完整',
        code: "400",
        data: null
      });
    }

    // 插入弹幕
    const insertSql = `
      INSERT INTO confession_wall 
      (user_id, content, color, type, school_code, font_size)
      VALUES (?, ?, ?, ?, ?, ?)
    `;

    const [result] = await pool.execute(insertSql, [
      user_id,
      content,
      color,
      type,
      school_code || null,
      parseInt(fontSize)
    ]);

    // 获取新插入的弹幕信息
    const getBarrageSql = `
      SELECT 
        c.barrage_id,
        c.content,
        c.color,
        c.type,
        c.create_time,
        u.user_account as username,
        u.avatar_url
      FROM confession_wall c
      LEFT JOIN users u ON c.user_id = u.user_id
      WHERE c.barrage_id = ?
    `;

    const [barrageDetails] = await pool.execute(getBarrageSql, [result.insertId]);

    // 处理返回数据
    const processedBarrage = {
      ...barrageDetails[0],
      avatar_url: barrageDetails[0].avatar_url ? data_url + barrageDetails[0].avatar_url : null,
      create_time: barrageDetails[0].create_time
    };

    response.json({
      msg: 'success',
      code: "200",
      data: processedBarrage
    });

  } catch (error) {
    console.error('发送表白墙弹幕失败:', error);
    response.json({
      msg: '服务器错误',
      code: "500",
      error: error.message
    });
  }
}

module.exports = {
  getConfessionBarrages,
  sendConfessionBarrage
}